//
//  LMOAuthViewController.swift
//  WeiBo
//
//  Created by Li MAc on 2018/11/23.
//  Copyright © 2018 Li MAc. All rights reserved.
//

import UIKit
import SVProgressHUD

class LMOAuthViewController: UIViewController {

    private lazy var web = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       view = web
       view.backgroundColor = UIColor.white
        
        web.delegate = self
       web.scrollView.isScrollEnabled = false
        title = "微博登陆界面"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fotSize: 16, target: self, action: #selector(fanFunc), isBack: true)
        
        navigationItem.rightBarButtonItem
            = UIBarButtonItem(title: "自动填充", fotSize: 16, target: self, action: #selector(rightFunc), isBack: false)
        
        
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(LMAppKey)&redirect_uri=\(LMURI)"
        
        //URL 确定要访问的资源
        guard  let url = URL(string: urlString) else{
            return
        }
        //建立要访问的资源
        let req = URLRequest(url: url)
        //加载请求
        web.loadRequest(req)
    }
    
    @objc func fanFunc(){
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc func rightFunc(){
        let js = "document.getElementById('userId').value = '15170250330';" + "document.getElementById('passwd').value = 'Liwenjie2355160.';"
        
        web.stringByEvaluatingJavaScript(from: js)
    }

}


extension LMOAuthViewController : UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        
        
        print("加载请求 --\(request.url?.absoluteString)")
        //如果请求地址包含 LMURI 不加载页面 / 否则加载
        if request.url?.absoluteString.hasPrefix(LMURI) == false{
            return true
        }
        print("加载请求--\(request.url?.query)")
        if request.url?.query?.hasPrefix("code=") == false{
            //返回
            fanFunc()
            print("取消授权")
            return false
        }
        
        //获取授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        
        
        print("授权码 \(code)")
        //使用s授权码获取AccessTonken
        
        LMNetworkTools.shared.loadAT(code: code) { (isSuccess) in
            if !isSuccess{
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else{
                SVProgressHUD.showInfo(withStatus: "登陆成功")
                
                
                NotificationCenter.default.post(name: NSNotification.Name(LoginTure), object: nil)
                
                //
                self.fanFunc()
            }
        }
        return false
    }
    //页面加载时
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //当页面加载完毕时
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
